package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	cst "saleforce/sf-common/constant"
	proto "saleforce/sf-common/protoc/backend-user"
	resp "saleforce/sf-common/response"
	"saleforce/sf-common/utils"
)

// Check 权限判断
func Check() gin.HandlerFunc {
	return func(c *gin.Context) {
		value := c.Value(cst.Current_Login_User)
		m, ok := value.(map[string]any)
		if !ok {
			c.AbortWithStatusJSON(http.StatusOK, resp.Resp{}.Warning(401, "Your access is denied"))
			return
		}
		delete(m, "lang")
		toStruct, err := utils.MapToStruct[proto.GetUserResp](m)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusOK, resp.Resp{}.Warning(401, "Your access is denied"))
			return
		}
		menus := toStruct.Menus
		path := c.Request.URL.Path
		for _, menu := range menus {
			if menu.ApiUrl == path {
				c.Next()
				return
			}
		}
		c.AbortWithStatusJSON(http.StatusOK, resp.Resp{}.Warning(401, "Your access is denied"))
		return
	}
}
